package com.acerola.client;


import com.acerola.message.*;
import com.acerola.protocol.MessageCodecSharable;
import com.acerola.protocol.ProcotolFrameDecoder;
import com.acerola.thread.CustThreadPoolExecutor;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        CustThreadPoolExecutor custThreadPoolExecutor = new CustThreadPoolExecutor(1, 1, 1);
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        AtomicBoolean LOGIN = new AtomicBoolean(false);
        try {
            Bootstrap bootstrap = new Bootstrap();
            //连接超时异常
            bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,5000);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
//                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    // 用来判断是不是读空闲时间过长，或 写空闲时间过长
                    // 5s 内如果没有输入数据，会触发一个 IdleState#WRITER_IDLE 事件
                    ch.pipeline().addLast(new IdleStateHandler(0, 5, 0));
                    // ChannelDuplexHandler 可以同时作为入站和出站处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        //响应特殊事件
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            // 触发了写空闲事件
                            if (event.state() == IdleState.WRITER_IDLE) {
                                ctx.writeAndFlush(new PingMessage());
                            }
                        }
                    });
                    ch.pipeline().addLast("client handler", new ChannelInboundHandlerAdapter() {
                        //在建立连接后触发active事件
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            custThreadPoolExecutor.init();
                            ExecutorService poll = custThreadPoolExecutor.getCustThreadPoolExecutor();
                            poll.submit(new Runnable() {
                                @Override
                                public void run() {
                                    Scanner scanner = new Scanner(System.in);
                                    System.out.println("请输入用户名:");
                                    String userName = scanner.nextLine();
                                    System.out.println("请输入密码:");
                                    String password = scanner.nextLine();
                                    LoginRequestMessage message = new LoginRequestMessage(userName, password);
                                    ctx.writeAndFlush(message);
                                    log.debug("等待后续操作");
                                    try {
                                        //等待线程唤醒
                                        WAIT_FOR_LOGIN.await();
                                    } catch (InterruptedException e) {
                                        throw new RuntimeException(e);
                                    }
                                    log.debug(String.valueOf(LOGIN.get()));
                                    if (!LOGIN.get()) {
                                        ctx.channel().close();
                                        return;
                                    }
                                    while (true) {
                                        System.out.println("==================================");
                                        System.out.println("send [username] [content]");
                                        System.out.println("gsend [group name] [content]");
                                        System.out.println("gcreate [group name] [m1,m2,m3...]");
                                        System.out.println("gmembers [group name]");
                                        System.out.println("gjoin [group name]");
                                        System.out.println("gquit [group name]");
                                        System.out.println("quit");
                                        System.out.println("==================================");
                                        String command = scanner.nextLine();
                                        String[] s = command.split(" ");
                                        switch (s[0]) {
                                            case "send":
                                                ctx.writeAndFlush(new ChatRequestMessage(userName, s[1], s[2]));
                                                break;
                                            case "gsend":
                                                ctx.writeAndFlush(new GroupChatRequestMessage(userName, s[1], s[2]));
                                                break;
                                            case "gcreate":
                                                Set<String> set = new HashSet<>(Arrays.asList(s[2].split(",")));
                                                set.add(userName); // 加入自己
                                                ctx.writeAndFlush(new GroupCreateRequestMessage(s[1], set));
                                                break;
                                            case "gmembers":
                                                ctx.writeAndFlush(new GroupMembersRequestMessage(s[1]));
                                                break;
                                            case "gjoin":
                                                ctx.writeAndFlush(new GroupJoinRequestMessage(userName, s[1]));
                                                break;
                                            case "gquit":
                                                ctx.writeAndFlush(new GroupQuitRequestMessage(userName, s[1]));
                                                break;
                                            case "quit":
                                                ctx.channel().close();
                                                return;
                                            default:
                                                System.out.println("==================================");
                                                System.out.println("指令不存在,请重新输入");
                                        }
                                    }
                                }
                            });
                            custThreadPoolExecutor.destroy();
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            log.debug("msg:{}", msg);
                            if (msg instanceof LoginResponseMessage) {
                                LoginResponseMessage loginResponseMessage = (LoginResponseMessage) msg;
                                if (loginResponseMessage.isSuccess()) {
                                    LOGIN.set(true);
                                }
                                WAIT_FOR_LOGIN.countDown();
                            }
                            if (msg instanceof ChatResponseMessage) {
                                ChatResponseMessage chatResponseMessage = (ChatResponseMessage) msg;
                                String from = chatResponseMessage.getFrom();
                                String content = chatResponseMessage.getContent();
                                System.out.println("用户" + "'" + from + "'" + "对你说:" + content);
                            }
                            if (msg instanceof GroupCreateResponseMessage) {
                                GroupCreateResponseMessage groupCreateResponseMessage = (GroupCreateResponseMessage) msg;
                                String reason = groupCreateResponseMessage.getReason();
                                System.out.println("群聊消息:" + reason);
                            }
                            if (msg instanceof GroupChatResponseMessage) {
                                GroupChatResponseMessage groupChatResponseMessage = (GroupChatResponseMessage) msg;
                                String content = groupChatResponseMessage.getContent();
                                String from = groupChatResponseMessage.getFrom();
                                System.out.println("群聊消息:" + "用户" + "'" + from + "'" + "说:" + content);
                            }
                        }

                    });
                }
            });
            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
